import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
// import 'package:imclient/imclient.dart';
// import 'package:imclient/message/message.dart';
// import 'package:imclient/model/channel_info.dart';
// import 'package:imclient/model/conversation.dart';
// import 'package:imclient/model/group_info.dart';
// import 'package:imclient/model/group_member.dart';
// import 'package:imclient/model/read_report.dart';
// import 'package:imclient/model/user_info.dart';
// import 'package:imclient/model/user_online_state.dart';
// import 'package:rtckit/rtckit.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/AppConfig/LocalStorage.dart';
import 'package:sph_shipper/FandCar/FindCarmain.dart';
import 'package:sph_shipper/Order/OrderList.dart';
import 'package:sph_shipper/SendGoods/SendGoodsMain.dart';
import 'package:url_launcher/url_launcher.dart';
// import 'package:wfc_example/app_server.dart';
// import 'package:wfc_example/config.dart';
// import 'package:wfc_example/default_portrait_provider.dart';

import '../Main/PersonCenter.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import '../l10n/messages.dart';

class TabbarView extends StatefulWidget {
  const TabbarView({super.key, required this.pateIndex});
  final int pateIndex;
  @override
  State<TabbarView> createState() => _TabbarViewState();
}

class _TabbarViewState extends State<TabbarView> {

  int currentPage =0;
  String cityVersion="";
  List CityListData=[];
  List pages = [SendGoodsMain(), FindCarMain(), OrderList(),PersonCenter()];
  @override
  void initState() {
    super.initState();
    // getCityVersion();
    // getUserMessageAction();
    getAPPVersion();
    if (widget.pateIndex!=null) currentPage=widget.pateIndex;

  }
  void getUserMessageAction() async {
    getApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      MyServiceUrl.getLoginUser, // 您的API端点
      {}, // 查询参数，如果没有可以传递null
          (responseData) async {
            await UserIdManager.saveUserID(responseData['data']['id']);
      },
    );
  }
  void getAPPVersion(){
    NoLoadinggetApiManager.getData(
      context,
      "api/system/dev/dict/list",
      {'category':'BIZ','parentId':'1808424071131934722'},
          (responseData)  {
        setState(() {
            if(responseData['data'][0]['extJson']!="v1.0.0"){
              showDialog(
                barrierDismissible: false,
                context: context,
                builder: (BuildContext context) {
                  return Align(
                    alignment: Alignment.center,
                    child: BrnDialog(
                      titleText: "温馨提示",
                      messageText: "速配货有新的版本上线，请前往更新。",
                      actionsWidget: [
                        TextButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: Text(
                            "下次再说",
                            style: TextStyle(color: MyColors.textColor, fontSize: 14.sp),
                          ),
                        ),
                        TextButton(
                          onPressed: ()async {
                            Navigator.pop(context);
                            const url = 'https://www.sph56.cn';
                            if (await canLaunch(url)) {
                            await launch(url);
                            } else {
                            throw 'Could not launch $url';
                            }
                          },
                          child: Text(
                            "现在就去",
                            style: TextStyle(color: MyColors.themeColor, fontSize: 14.sp),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              );
            }
        });

      },
    );
  }
  // void getCityVersion() async {
  //   dio.interceptors.add(InterceptorsWrapper(
  //String? token = await TokenManager.getToken();
  //       onRequest: (options, handler) {
  //         options.headers["satoken"] = token;
  //         return handler.next(options);
  //       }
  //   ));
  //
  //   dio.get<String>(MyServiceUrl.header+'api/webapp/dev/cityDict/version')
  //       .then((r) {
  //     setState(()   {
  //       print(r);
  //       Map<String, dynamic> jsonMap = json.decode(r.toString());
  //
  //       // 获取code和data
  //       String code = jsonMap['code'].toString();
  //       String data = jsonMap['data'].toString();
  //       if (code == "200") {
  //       /*  checkCityVersion();
  //
  //         if(cityVersion!=jsonMap['data'].toString())
  //            CityListVersionManager.saveCityListVersion( jsonMap['data'].toString());*/
  //           // getCityList();
  //
  //       } else {}
  //       // 打印结果
  //       print('Code: $code');
  //       print('data: $data');
  //     });
  //   }).catchError((error) {
  //     print(error);
  //   });
  // }

  // void  checkCityVersion()async{
  //   String? cityListVersion = await CityListVersionManager.getCityListVersion() as String?;
  //   cityVersion=cityListVersion!;
  //   print("cityListVersion:$cityListVersion");
  // }
  // void getCityList() async {
  //String? token = await TokenManager.getToken();
  //   dio.interceptors.add(InterceptorsWrapper(
  //       onRequest: (options, handler) {
  //         options.headers["satoken"] = token;
  //         return handler.next(options);
  //       }
  //   ));
  //
  //   dio.get<String>(MyServiceUrl.header+'api/system/dev/cityDict/tree')
  //       .then((r) {
  //     setState(() {
  //       print(r);
  //       Map<String, dynamic> jsonMap = json.decode(r.toString());
  //
  //       // 获取code和data
  //       String code = jsonMap['code'].toString();
  //       if (code == "200") {
  //         List data = jsonMap['data'];
  //         // print(r.data);
  //       CityListData =data;
  //
  //         print("CityListData:$CityListData");
  //         // getCityListData();
  //       } else {}
  //       // 打印结果
  //       print('Code: $code');
  //     });
  //   }).catchError((error) {
  //     print(error);
  //   });
  // }

  // void getCityListData()async{
  //   await CityListManager.saveCityList(CityListData.toString());
  //   String? cityList = await CityListManager.getCityList() as String?;
  // }
  DateTime? lastPressed;
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    return WillPopScope(
        onWillPop: () async {
          print("再按一次退出");
          // 获取当前时间
          final now = DateTime.now();
          // 如果 lastPressed 为空或者间隔时间超过 2 秒，则更新 lastPressed 并提示用户
          if (lastPressed == null || now.difference(lastPressed!) > Duration(seconds: 2)) {
            lastPressed = now;
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('再按一次退出'),
                duration: Duration(seconds: 2),
              ),
            );
            return false; // 不退出
          }
          return true; // 退出应用
      // // 返回false禁用手势返回
      // return Future.value(false);
    },
    child:
      Scaffold(
      bottomNavigationBar: BottomNavigationBar(
          backgroundColor: Colors.white,
          items: [
            BottomNavigationBarItem(
              icon:currentPage==0? Image.asset('lib/Images/TabBar/发货黄.png',height: 22.h,width: 22.w,):Image.asset('lib/Images/TabBar/发货灰.png',height: 22.h,width: 22.w,),
              label: messages['发货'],
            ),
            BottomNavigationBarItem(
              icon:currentPage==1? Image.asset('lib/Images/TabBar/找车黄.png',height: 20.h,width: 20.w,):Image.asset('lib/Images/TabBar/找车灰.png',height: 20.h,width: 20.w,),
              label: messages['找车'],
            ),

            BottomNavigationBarItem(
              icon:Stack(
                children: [
                  currentPage==2? Image.asset('lib/Images/TabBar/运单黄.png',height: 15.h,width: 20.w,):Image.asset('lib/Images/TabBar/运单灰.png',height: 15.h,width: 20.w,),
                  Positioned(
                    top: 0,
                      right: 0,
                      child:  Badge(backgroundColor: Colors.red,),)
                ],
              ),
              label: messages['运单'],
            ),
            BottomNavigationBarItem(
              icon:currentPage==3? Image.asset('lib/Images/TabBar/我的黄.png',height: 15.h,width: 20.w,):Image.asset('lib/Images/TabBar/我的灰.png',height: 15.h,width: 20.w,),
              label: messages['我的'],
            ),],

          type: BottomNavigationBarType.fixed, currentIndex: currentPage,onTap: (index){
        setState(() {
          currentPage=index;

        });

      },selectedItemColor: MyColors.themeColor),
      body: pages[currentPage],
      ),
    );
  }
}
